<template>
  <div class="box">
    <span class="returnBtn" @click="backApplicationCenter">返回应用中心</span>
    <span v-if="showBackHomeBtn" class="returnBtn" @click="backHome">返回首页</span>
    <a-dropdown v-if="currentUser && currentUser.userName" placement="bottomRight">
      <span class="ant-pro-account-avatar">
        <!-- <a-avatar
        size="small"
        src="https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png"
        class="antd-pro-global-header-index-avatar"
      /> -->
        <span class="name">
          {{
            (userInfo.sysRole && userInfo.sysRole.roleName) ||
            (userInfo.personInfo && userInfo.personInfo.personName) ||
            userInfo.userName
          }}
        </span>
      </span>
      <template v-slot:overlay>
        <a-menu class="ant-pro-drop-down menu" :selected-keys="[]">
          <a-menu-item v-for="(item, index) in userInfo.roleList" :key="index" @click="over(item)">
            <a-icon type="user" />
            {{ item.roleName }}
          </a-menu-item>
          <a-menu-divider v-if="userInfo.roleList.length > 0" />
          <a-menu-item v-if="userInfo.sysSource == 2" key="edit" @click="passwordEdit">
            <a-icon type="edit" />
            修改密码
          </a-menu-item>
          <a-menu-item key="logout" @click="handleLogout">
            <a-icon type="logout" />
            退出登录
          </a-menu-item>
        </a-menu>
      </template>
    </a-dropdown>
    <a-modal
      title="修改密码"
      width="30%"
      :maskClosable="false"
      okText="确定"
      cancelText="取消"
      :visible="passwordShow"
      @ok="sure"
      @cancel="cancel"
    >
      <a-form-model
        ref="form"
        :rules="dialog.rules"
        :model="dialog.form"
        :label-col="{ span: 4, style: 'width:110px;' }"
        :wrapper-col="{ span: 14, style: 'width:calc(100% - 110px)' }"
      >
        <a-row :gutter="10">
          <a-col :xl="24" :lg="24" :md="24">
            <a-form-model-item label="输入旧密码" prop="oldPwd">
              <a-input-password v-model="dialog.form.oldPwd" autocomplete="new-password"></a-input-password>
            </a-form-model-item>
            <a-form-model-item label="输入新密码" prop="password">
              <a-input-password v-model="dialog.form.password" autocomplete="new-password"></a-input-password>
            </a-form-model-item>
            <a-form-model-item label="确认新密码" prop="qrpassword">
              <a-input-password v-model="dialog.form.qrpassword" autocomplete="new-password"></a-input-password>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { Modal } from 'ant-design-vue'
import { mapGetters } from 'vuex'
import { roleOver, changePassword } from '@/api/login'
import router from '@/router'
export default {
  name: 'AvatarDropdown',
  computed: {
    ...mapGetters(['userInfo', 'showBackHomeBtn']),
  },
  inject: ['reload'],
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'))
      } else if (
        !/^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{16,100}$/.test(
          value
        )
      ) {
        callback(new Error('请输入16位及以上字符，至少包含数字、大写字母、小写字母、特殊字符中的三种类型!'))
      } else {
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入新密码'))
      } else if (value !== this.dialog.form.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      showBackhomBtn: undefined,
      passwordShow: false,
      dialog: {
        form: {
          password: '',
          qrpassword: '',
          oldPwd: '',
        },
        rules: {
          password: [
            {
              required: true,
              validator: validatePass,
              trigger: 'blur',
            },
          ],
          oldPwd: [
            {
              required: true,
              message: '请输入旧密码',
              trigger: 'blur',
            },
          ],
          qrpassword: [
            {
              required: true,
              validator: validatePass2,
              trigger: 'blur',
            },
          ],
        },
      },
    }
  },
  props: {
    currentUser: {
      type: Object,
      default: () => null,
    },
    menu: {
      type: Boolean,
      default: true,
    },
  },
  methods: {
    //返回首页
    backHome() {
      var url = window.location.hash.split('/')[1]
      this.$router.push({
        name: url + 'Home',
      })
    },
    //返回应用中心
    backApplicationCenter() {
      this.$router.push({
        path: '/home',
      })
    },
    //修改密码
    passwordEdit() {
      this.passwordShow = true
    },
    sure() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          changePassword({ userPwd: this.dialog.form.qrpassword, oldPwd: this.dialog.form.oldPwd }).then((res) => {
            // console.log(res)
            this.cancel()
            this.$message.success('修改成功')
          })
        }
      })
    },
    cancel() {
      this.passwordShow = false
      this.$refs.form.resetFields()
    },
    //切换角色
    over(e) {
      roleOver(e.roleId).then((res) => {
        this.$store.dispatch('GetInfo').then((res) => {
          var roles = res.menuList || []
          this.$store
            .dispatch('GenerateRoutes', {
              roles,
              topath: this.$router.path,
            })
            .then((info) => {
              this.$store.commit('setpanes', false)
              router.addRoutes(this.$store.getters.addRouters)
              this.$nextTick(() => {
                this.$router.push({
                  path: '/',
                })
              })
              this.reload()
            })
        })
      })
    },
    handleLogout(e) {
      Modal.confirm({
        title: '信息',
        content: '您确定要注销吗？',
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          return this.$store.dispatch('Logout').then(() => {
            this.$router.push({ name: 'loginAdmin' })
          })
        },
        onCancel() {},
      })
    },
  },
}
</script>

<style lang="less" scoped>
.box {
  display: flex;
  justify-content: space-between;
  .returnBtn {
    padding-left: 5px;
    color: #4870ad;
    font-size: 14px;
    cursor: pointer;
  }
  .ant-pro-account-avatar {
    color: #fff;
    // display: flex;
    align-items: center;
    .name {
      margin-left: 5px;
      color: var(--font-color);
      max-width: 128px;
      overflow: hidden;
      display: block;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
}

.ant-pro-drop-down {
  /deep/ .action {
    margin-right: 8px;
  }
  /deep/ .ant-dropdown-menu-item {
    min-width: 200px;
  }
}
</style>
